package com.github.icloudpay.pay.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * xml解析
 * @author hexufeng
 *
 */
public class XmlAnalysis {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(XmlAnalysis.class);

	/**
	 * 微信回调xml解析
	 * @return
	 */
	public static Map<String, Object> wechatCallBackXml(HttpServletRequest request) throws IOException, SAXException{

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		String FEATURE = null;
		try {
			FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
			dbf.setFeature(FEATURE, true);

			FEATURE = "http://xml.org/sax/features/external-general-entities";
			dbf.setFeature(FEATURE, false);

			FEATURE = "http://xml.org/sax/features/external-parameter-entities";
			dbf.setFeature(FEATURE, false);

			FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
			dbf.setFeature(FEATURE, false);

			dbf.setXIncludeAware(false);
			dbf.setExpandEntityReferences(false);

		} catch (ParserConfigurationException e) {
			logger.info("ParserConfigurationException was thrown. The feature '" +
					FEATURE + "' is probably not supported by your XML processor.");
		}

		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			DocumentBuilder safebuilder = dbf.newDocumentBuilder();
			InputStream is =  request.getInputStream();
			Document document = safebuilder.parse(is);

			//获取到document里面的全部结点
			NodeList allNodes = document.getFirstChild().getChildNodes();
			Node node;
			int i=0;
			while (i < allNodes.getLength()) {
				node = allNodes.item(i);
				if(node instanceof Element){
					paramMap.put(node.getNodeName(),node.getTextContent());
				}
				i++;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		return paramMap;
	}

}
